package org.chy.config.redis.impl;

import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.chy.config.redis.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * @author  chenghy
 * @date    2018年01月14日 22时21分45秒
 * @Description 发上等愿,结中等缘,享下等福;向高处立,就平处坐,从宽处行.
 * @Package org.chy.config.redis
 */
@Service("redisService")
@SuppressWarnings({ "rawtypes", "unchecked" })
public class RedisServiceImpl implements RedisService {
	
	private static final Logger logger = LoggerFactory.getLogger(RedisServiceImpl.class);
	 
	private @Autowired RedisTemplate redisTemplate;

	@Override
	public boolean set(String key, Object value) {
		boolean result = false;
		try {
			ValueOperations<String, Object> operations = redisTemplate.opsForValue();
			operations.set(key, value);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("redis write info ......");
		}
		return result;
	}
	
	@Override
	public boolean set(String key, Object value, Long expireTime) {
		boolean result = false;
		try {
			ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
			operations.set(key, value);
			redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("");
		}
		return result;
	}

	@Override
	public Object get(String key) {
		ValueOperations<String, Object> operations = redisTemplate.opsForValue();
		return operations.get(key);
	}
 
	@Override
	public boolean exists(String key) {
		return redisTemplate.hasKey(key);
	}
	
	@Override
	public void remove(String key) {
		if(exists(key)) {
			redisTemplate.delete(key);
		}
	}
	
	@Override
	public void removePattern(String pattern) {
		Set<Serializable> keys = redisTemplate.keys(pattern);
		if(keys.size() > 0) {
			redisTemplate.delete(keys);
		}
	}
	
	@Override
	public void remove(String... keys) {
		for(String key : keys) {
			remove(key);
		}
	}
}
